package com.finger.forest.http;

import android.util.Log;

import com.finger.forest.R;
import com.finger.forest.base.BaseApplication;
import com.finger.forest.model.BaseModel;
import com.finger.forest.utils.ToastUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.HttpException;
import retrofit2.Response;

public abstract class XPCallback implements Callback {
    private final static String TAG = "XPCallback";
    //网络请求失败,请稍后重试
    public final static String NET_FAIL = BaseApplication.getInstance().getString(R.string.net_fail);
    //网络连接失败,请稍后重试
    public final static String CONN_FAIL = BaseApplication.getInstance().getString(R.string.conn_fail);
    //证书验证失败
    public final static String SSL_FAIL = BaseApplication.getInstance().getString(R.string.ssl_fail);
    //数据有误
    public final static String DATA_FAIL = BaseApplication.getInstance().getString(R.string.data_fail);
    //获取数据失败
    public final static String GET_DATA_FAIL = BaseApplication.getInstance().getString(R.string.get_data_fail);
    //TOKEN失效
    public final static String TOKEN_INVALID = BaseApplication.getInstance().getString(R.string.token_invalid);


    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    @Override
    public void onResponse(Call call, Response response) {
        dealSuccessResult(response);
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        dealErrorResult(t);
    }

    /**
     * 处理请求失败的结果
     */
    private void dealErrorResult(Throwable e) {
        String message = "";
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            switch (httpException.code()) {
                case UNAUTHORIZED:
                case FORBIDDEN:
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                    message = NET_FAIL + "code = " + httpException.code();
                    break;
                default:
                    message = NET_FAIL;
                    break;
            }
        } else if (e instanceof ConnectException
                || e instanceof SocketTimeoutException
                || e instanceof UnknownHostException) {
            message = CONN_FAIL;
        } else if (e instanceof SSLHandshakeException) {
            message = SSL_FAIL;
        } else {
            message = "网络不稳定，请稍后重试";
        }
        ToastUtils.show(message);
        Log.e(TAG, "======error======\n" + e.getMessage());
        onError(message, e);
    }

    /**
     * 处理请求成功的结果
     */
    private void dealSuccessResult(Response response) {
        if (response.isSuccessful()) {
            //响应成功
            if (response.body() instanceof BaseModel) {
                BaseModel baseEntity = (BaseModel) response.body();
                if (null != baseEntity.getRst()) {
                    if (null == baseEntity) {
                        //  数据为空
                        ToastUtils.show(DATA_FAIL);
                        onError(baseEntity.getMsg() == null ? "" : baseEntity.getMsg(), null);
                        return;
                    }
                    if (baseEntity.getCode() == 1) {
                        onSuccess(baseEntity.getCode(), baseEntity);
                    }
//                else if (baseEntity.getResp_code() == 401) {
//                    //  token失效
//                    ToastUtils.show(TOKEN_INVALID);
//                    onError(baseEntity, null);
//                }
                    else {
                        ToastUtils.show(baseEntity.getMsg());
                        onError(baseEntity.getMsg() == null ? "" : baseEntity.getMsg(), null);
                    }
                } else {
                    onSuccess(baseEntity.getCode(), baseEntity);
                }
            } else {
//                try {
//                    JSONObject jsonObject = new JSONObject(response.body().toString());
//                    int code = jsonObject.getInt("code");
//                    if (code == 1) {
//                        BaseModel model = new BaseModel();
//                        model.setCode(1);
//                        model.setMsg(jsonObject.getString("msg"));
//                        onSuccess(code, model);
//                    } else {
//                        onError("网络波动异常，请稍后重试", null);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                onError("网络不稳定，请稍后重试", null);
            }

        } else {
            //TODO   响应失败
            onError("网络不稳定，请稍后重试", null);
        }
    }

    //成功的回调
    public abstract void onSuccess(int code, BaseModel baseEntity);

    //失败的回调
    public abstract void onError(String baseEntity, Throwable t);
}
